/**
 * {time:开始时间,words:'歌词'}
 * @param {*} data 
 */
function parseLrc(lrc){
    let lines = lrc.split('\n')
    let result = []
    for(var i=0;i<lines.length;i++){
        let str = lines[i]
        let parts = str.split(']')
        // console.log(parts)
        let timeStr = parts[0].substring(1);
        let time = parseTime(timeStr)
        let obj = {
            time,
            words:parts[1]
        }
        result.push(obj);
    }
    return result;

}
/**
 * 处理时间
 */
function parseTime(timeStr){
   let parts =  timeStr.split(':')
   return +parts[0] * 60 + +parts[1]
}


let result  = parseLrc(lrc)
// console.log(result)z

var doms = {
    audio:document.querySelector('audio'),
    ul:document.querySelector('.container ul'),
    container:document.querySelector('.container')
};


/**
 * 找播放歌词的下标
 */
function findIndex(){
    // console.log(audio1)
    let audio = document.querySelector('audio')
    currentTime = audio.currentTime
    for(var i=0;i<result.length;i++){
        if(currentTime<result[i].time){
            return i-1;
        }
    }
    return result.length-1;
}
/**
 * 创建界面
 */
function createLrcELements(){
    // 文档片段
    var frag = document.createDocumentFragment()
    for(var i=0;i<result.length;i++){
        var li = document.createElement('li');
        li.textContent =result[i].words
        frag.appendChild(li)
    }
    doms.ul.appendChild(frag)
}
createLrcELements()

// 容器高度
var containerHeight = doms.container.clientHeight;
// 歌词高度
var liHeight = doms.ul.children[0].clientHeight
// 最大偏移量
var  maxOffset = doms.ul.clientHeight-containerHeight

/**
 * ul 偏移量
 */
function setOffset(){
    var index = findIndex();
    var offset = liHeight*index+liHeight/2 - containerHeight/2
    // console.log(offset)
    if(offset<0){
        offset = 0
    }
    if(offset>maxOffset){
        offset = maxOffset
    }
    doms.ul.style.transform =  `translateY(-${offset}px)`
    var li = doms.ul.querySelector('.active')
    if(li){
        li.classList.remove('active')
    }
    li = doms.ul.children[index]
    if(li){
        li.classList.add('active')
    }
    
}
doms.audio.addEventListener('timeupdate',setOffset)
